package com.example.testsbjenkins.zip;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.util.StopWatch;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;

/**
 * @author: lt
 * @date: 2022/7/25 14:55
 * @Description: todo
 */
public class Files2TarUtil {

    /**
     * 将文件打成tar 不压缩
     * @param target
     * @param sources
     * @return
     * @throws IOException
     */
    public static File pack(File target, File[] sources) throws IOException {

        FileOutputStream out = new FileOutputStream(target);
        TarArchiveOutputStream os = new TarArchiveOutputStream(out);
        for (File file : sources) {
            os.putArchiveEntry(new TarArchiveEntry(file, file.getName()));
            IOUtils.copy(new FileInputStream(file), os);
            os.closeArchiveEntry();
        }
        return target;
    }
    /**
     * 将文件打成tar 不压缩
     * @param target
     * @param sources
     * @return
     * @throws IOException
     */
    public static File packByChannel(File target, File[] sources) throws IOException {

        FileOutputStream out = new FileOutputStream(target);
        TarArchiveOutputStream os = new TarArchiveOutputStream(out);

        WritableByteChannel writableByteChannel = Channels.newChannel(os);
        for (File file : sources) {
            os.putArchiveEntry(new TarArchiveEntry(file, file.getName()));
            //IOUtils.copy(new FileInputStream(file), os);
            FileChannel fileChannel = new FileInputStream(file).getChannel();
            fileChannel.transferTo(0,file.length(),writableByteChannel);
            os.closeArchiveEntry();
        }
        return target;
    }
    
    
    

    public static void main(String[] args) throws IOException {
        String pathname = "C:\\Users\\Administrator.DESKTOP-4PCK80Q\\Desktop\\test\\2\\t";
        File file = new File(pathname);

        File[] sources = file.listFiles();
        File target = new File("C:\\Users\\Administrator.DESKTOP-4PCK80Q\\Desktop\\test\\tar\\release_package.tar");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        packByChannel(target, sources);
        stopWatch.stop();
        System.out.println("耗时:" + stopWatch.getLastTaskTimeMillis() / 1000 + "s");
    }
}
